package models

import "database/sql"

type User struct {
	ID       int64  `json:"id"`
	UserName string `json:"username"`
	PassWord string `json:"password"`
}

// RecordkCollection is collection of Tasks
type UserCollection struct {
	Users []User `json:"items"`
}

func Login(db *sql.DB, username string, password string) UserCollection {
	sql := "SELECT id,username,password FROM users WHERE username = ? AND password = ?"

	rows, err := db.Query(sql, username, password)
	if err != nil {
		panic(err)
	}
	defer rows.Close()

	result := UserCollection{}
	for rows.Next() {
		user := User{}
		err = rows.Scan(&user.ID, &user.UserName, &user.PassWord)
		if err != nil {
			panic(err)
		}
		result.Users = append(result.Users, user)
	}
	return result
}

func GetUser(db *sql.DB, id int64) (UserCollection, error) {
	sql := "SELECT id,username,password FROM users WHERE id=?"

	rows, err := db.Query(sql, id)
	if err != nil {
		return UserCollection{}, err
	}

	defer rows.Close()

	result := UserCollection{}
	for rows.Next() {
		user := User{}
		err := rows.Scan(&user.ID, &user.UserName, &user.PassWord)
		if err != nil {
			return UserCollection{}, err
		}
		result.Users = append(result.Users, user)
	}
	return result, err
}

func PutUser(db *sql.DB, username string, password string) (int64, error) {
	sql := "INSERT INTO users(username,password) VALUES(?,?)"

	stmt, err := db.Prepare(sql)

	if err != nil {
		panic(err)
	}

	defer stmt.Close()

	result, err2 := stmt.Exec(username, password)

	if err2 != nil {
		panic(err2)
	}

	return result.LastInsertId()
}
